<?php 
namespace Admin\Controller; 
use Think\Controller;
class RbacController extends CommonController{
	//角色列表
	public function role(){
		$this->role= M('role')->select();
		$this->display();
	}
	//添加角色
	public function addRole(){
		$this->display();
	}
	//添加角色表单处理
	public function addRoleHandle(){
		if(!IS_POST) $this->error("提交方式错误");
		if(M('role')->add(I())){
			$this->success("添加成功",__CONTROLLER__.'/role');
		}else{
			$this->error("添加失败",__CONTROLLER__.'/role');
		}
	}	
	//节点列表
	public function node(){
		$field =array('id','name','title','pid');
		$node = M('node')->field($field)->order('sort')->select();
		$this ->node = node_merge($node);
		$this->display();
	}
	//添加节点
	public function addNode(){ 
		$this->pid = I('pid',0,'intval');
		$this->level = I('level',1,'intval');
		switch ($this->level) {
			case 1:
				$this->type = "应用";
				break;
			case 2:
				$this->type= "控制器";
				break;
			case 3:
				$this->type= "方法";
				break;
		}
		$this->display();
	}
	//添加节点处理表单
	public function addNodeHandle(){
		if(!IS_POST) $this->error("提交方式错误");
		if(M('node')->add(I())){
			$this->success("添加成功",__CONTROLLER__.'/node');
		}else{
			$this->error("添加失败",__CONTROLLER__.'/node');
		}
	}
	//修改节点
	public function editNode(){
		$node = M('node')->where(array('id'=>I('id')))->select();
		switch ($node[0]['level']) {
			case 1:
				$this->type = "应用";
				break;
			case 2:
				$this->type= "控制器";
				break;
			case 3:
				$this->type= "方法";
				break;
		}
		$this->node = $node[0];
		$this->display();
	}
	//修改节点处理表单
	public function editNodeHandle(){
		$data['id']     = I('id','','intval');
		$data['name']   = I('name');
		$data['title']  = I('title');
		$data['status'] = I('status');
		$data['sort']   = I('sort');
		$result = M('node')->save($data);
		if($result){
			$this->success("修改成功",__CONTROLLER__.'/node');
		}else{
			$this->error("修改失败",__CONTROLLER__.'/node');
		}
	}	
	//配置权限
	public function access(){
		$rid = I ('rid','','intval');
		$field=array('id','name','title','pid');
		$node = M('node')->order('sort')->field($field)->select();
		$access =M('access')->where(array('role_id'=>$rid))->getField('node_id',true);

		$this->node = node_merge($node,$access);
		$this->rid  = $rid;
		$this->display();
	}
	//更新权限信息
	public function accessHandle(){
		$db = M('access');
		$rid=I('rid','','intval');
		$data = array();
		//清空原权限
		//p(I('access'));die;
		$db->where(array('role_id'=>$rid))->delete();
		foreach (I('access') as $v) {
			$tmp =explode('_', $v);
			$data[] =array(
				'role_id' => $rid,
				'node_id' => $tmp[0],
				'level' => $tmp[1],
			);
		}
		//更新权限
		$result = $db ->addAll($data);
		if($result){
			$this->success("修改成功");
		}else{
			$this->error("修改失败");
		}
	}
}

